package com.heima.common.util;

import com.heima.utils.common.AppJwtUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class RequestContextUtil {

    /**
     * 获取指定请求头信息
     * 1.获取HttpServletRequest
     * 2.通过HttpServletRequest
     */
    public static String getHeaders(String headerName){
        //RequestContextHolder.getRequestAttributes()表示获取当前线程请求中的信息，RequestContextHolder相当于上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //获取HttpServletRequest
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getHeader(headerName);

    }

    /**
     * 获取token，并且解析
     */
    public static Map<String,Object>getToken(){
        //获取令牌
        String token = getHeaders("token");
        //解析令牌
        Map<String, Object> body = AppJwtUtil.getClaimsBody(token);
        return body;

    }

    /**
     * 从token中获取指定数据
     * @param key
     * @return
     */
    public static <T>T getNode(String key){
        //获取token数据
        Map<String, Object> tokenMap = getToken();
        //获取指定key的值
        return (T)tokenMap.get(key);
    }





}
